<template>
  <div>
    <el-collapse value="common" v-if="showDevice">
      <el-collapse-item title="组件关联设备" name="common">
        <div class="pad-lft-rgt-10">
          <div v-for="(item, index) in devices" :key="index">
            <div class="flex-com mar-btm">
              <span class="label-title">组件设备:</span>
              {{item.deviceName}}
            </div>
            <div class="flex-com mar-btm">
              <span class="label-title">关联设备:</span>
              <el-select v-model="item._id" @change="(value) => choseDevice(value, item.id)" size="mini"
                         placeholder="关联设备名称" class="width-input">
                <el-option v-for="(list, index) in deviceList" :key="index" :label="list.deviceName"
                           :value="list._id" :disabled="item.protocolId!==list.protocolId"></el-option>
                <el-option v-if="!deviceList.some(option=>option._id===item._id)" label="请选择关联的设备"
                           :value="item._id"></el-option>
              </el-select>
            </div>
          </div>
        </div>
      </el-collapse-item>
    </el-collapse>
    <EmptyContent v-else-if="!showDevice && widget.logicList && widget.logicList.length===0" :min-height="300"
                  :image-size="120" empty-text="暂无设备"></EmptyContent>
    <div v-if="showDevice" class="mar-auto">
      <el-button
	      type="primary" size="small" @click="syncRule"
	      :disabled="!isSync">同步真值反馈规则</el-button>
    </div>
  </div>
</template>
<script>
  import {WidgetClass} from "@/modules/IDE/widget/atom/widget";
  import {messageHandle} from "@/utils";
  import {msgCode} from "@/config/string";
  import {mapState} from "vuex";

  export default {
    name: 'ComponentSpec',
    props: {
      widget: {
        type: WidgetClass,
        default: () => {
          return {};
        }
      }
    },
    data() {
      return {}
    },
    computed: {
      ...mapState({
	      globalDeviceList: state => state.ide.globalDeviceList,
	      globalLogicList: state => state.ide.globalLogicList,
      }),
      widgetListLen() {
        return this.globalLogicList.filter((item => {
          return item.widgetId === this.widget.id
        })).length || 0
      },
      deviceList() {
        //组合自定义命令和设备命令到一个组
        return this.globalDeviceList.map(device => {
          const commandList = [];
          const {customCommand, commands} = device;
          if (customCommand && customCommand.length > 0) {
            commandList.push({
              label: "自定义命令",
              options: customCommand,
              value: 0,
            });
          }
          if (commands && commands.length > 0) {
            commandList.push({
              label: "设备命令",
              options: commands,
              value: 1,
            });
          }
          device.commandList = commandList;
          return device;
        });
      },
      showDevice() {
        const {devices = []} = this.widget;
        return devices.length > 0;
      },
      isSync() {
        //计算都关联了设备才同步规则
        let list = this.widget.devices.filter(w => w._id)
        return list.length === this.widget.devices.length && this.widgetListLen === 0
      },
      devices() {
        //复制项目的时候替换id
        const {devices = []} = this.widget;
        devices.forEach(item => {
          if (item._id) {
            item.id=  this.deviceList.find(device=>device.protocolId===item.protocolId)._id
            item._id = item.id
          }
        })
        return devices
      }
    },
    methods: {
      submitLogicRule(params) {
        API.roomLogicRule.roomLogicRuleAdd(params).then(() => {
          this.showRuleDialog = false;
          messageHandle({code: msgCode.SYNC_SUCCESS, title: "规则"});
        }).catch((err) => {
          console.log("err: ", err);
        });
      },
      replace(str, oldStr, newStr) {
        return str.replace(oldStr, newStr);
      },
      actionTrans(events, oldVal, newVal) {
        if (events.type === 'deviceCtl' && events.value.device === oldVal) {
          events.value.device = newVal;
        } else if (events.value.type === 'relatedDeviceStatus' && events.value.controlId === oldVal) {
          events.value.controlId = newVal;
          events.value.value = this.replace(events.value.value, oldVal, newVal);
        } else if (events.type === 'logicCmd') {
          //替换逻辑处理里面的deviceID
          const reg = new RegExp(oldVal, 'g');
          events.value.value = events.value.value.replace(reg, newVal);
        }
      },
      commonTransDevice(actions, oldVal, newVal) {
        if (actions.length > 0) {
          actions.forEach((action) => {
            //判断条件替换
            if (action.value && action.value.conditions && action.value.conditions.length > 0) {
              action.value.conditions.forEach(conditions => {
                if (conditions.value1.type === 'relatedDeviceStatus' && conditions.value1.controlId === oldVal) {
                  conditions.value1.controlId = newVal;
                  conditions.value1.value = this.replace(conditions.value1.value, oldVal, newVal);
                }
              });
            }
            //满足行为替换
            if (action.value && action.value.actions && action.value.actions.length > 0) {
              action.value.actions.forEach(events => {
                this.actionTrans(events, oldVal, newVal);
              });
            }
            //不满足行为替换
            if (action.value && action.value.elseActions && action.value.elseActions.length > 0) {
              action.value.elseActions.forEach(events => {
                this.actionTrans(events, oldVal, newVal);
              });
            }
          })
        }
      },
      // 获取组件及其所有子组件平铺数组
      choseDevice(newVal, oldVal) {
        const recurseChildren = (widget = {}) => {
          widget.ports.events.forEach((event) => {
            this.commonTransDevice(event.action, oldVal, newVal);
            event.action.forEach((action) => {
              this.actionTrans(action, oldVal, newVal);
            });
          })
          if (widget.logicList && widget.logicList.length > 0) {
            widget.logicList.forEach((logic) => {
              //当触发条件是设备 就要替换
              if (logic.type === 'relatedDeviceStatus' && logic.controlId === oldVal) {
                logic.controlId = newVal;
                logic.value = this.replace(logic.value, oldVal, newVal);
              }
              this.commonTransDevice(logic.actions, oldVal, newVal);
            })
          }
          const {children = []} = widget;
          children.forEach(child => recurseChildren(child));
        };
        recurseChildren(this.widget);
      },
      syncRule() {
        this.widget.logicList.forEach((item) => {
          delete item._id;
          let params = {
            ...item,
            roomId: this.widget.roomId,
            widgetId: this.widget.id
          };
          this.submitLogicRule(params);
        })
      }
    }

  };
</script>
<style lang="less" scoped>
  .flex-com {
    display: flex;
    align-items: center;
    gap: 10px;
  }

  .label-title {
    display: inline-block;
    min-width: 60px;
    color: #666;
    font-size: 14px;
  }

  .state-input {
    /deep/ .el-input__inner {
      background: #f7f8fa;
      border: none;
      outline: none;
    }
  }

  .width-input {
    width: 100%;

    /deep/ .el-input__inner {
      background: #f7f8fa;
    }
  }

  .mar-auto {
    text-align: center;
    margin: 10px;
  }
</style>
